package cn.sxy.mybatis.binding;

import cn.sxy.mybatis.session.SqlSession;

import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * 映射器代理类
 */
public class MapperProxy<T>  implements InvocationHandler, Serializable {

    private static final Long serialVersionUID = -36458923764873492L;

    private SqlSession sqlSession;

    private final Class<T> mapperInterface;
    private final Map<Method,MapperMethod> methodCache;


    public MapperProxy(SqlSession sqlSession, Class<T> mapperInterface, Map<Method, MapperMethod> methodCache) {
        this.sqlSession = sqlSession;
        this.mapperInterface = mapperInterface;
        this.methodCache = methodCache;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        //如果是Object的方法则不需要代理直接返回
        if(Object.class.equals(method.getDeclaringClass())) {
            return method.invoke(this, args);
        }else{
            final MapperMethod mapperMethod = cachedMapperMethod(method);
            return mapperMethod.execute(sqlSession,args);
        }
    }

    //去cache中找MapperMethod
    private MapperMethod cachedMapperMethod(Method method) {
        MapperMethod mapperMethod = methodCache.get(method);

        if(mapperMethod == null) {
            //找不到->new
            mapperMethod=new MapperMethod(mapperInterface,method,sqlSession.getConfiguration());
            methodCache.put(method,mapperMethod);
        }
        return mapperMethod;
    }

}
